<?php
namespace app\admin\business;

use app\model\mysql\ProductSku;
use think\Exception;
use think\facade\Log;
use think\facade\Db;

class Product {

    protected $model = null;
    protected $skuModel = null;

    public function __construct() {
        $this->model = new \app\model\mysql\Product();
        $this->skuModel = new ProductSku();
    }

    public function save($data = []) : bool {

        Db::startTrans();
        try{
            $id = $data["id"] ??  0;
            if ($id > 0 ) {
                $this->model->where("id", $id);
            }
            $this->model->save([
                "title" => $data["title"],
                "category_id" => $data["category_id"],
                "category_path_id" => $data["category_path_id"],
                "promotion_title" => $data["promotion_title"],
                "sku" => $data["sku"],
                "url_key" => isset($data["url_key"]) ? $data["url_key"] : "",
                "unit" => $data["unit"],
                "keywords" => $data["keywords"],
                "sub_title" => $data["sub_title"],
                "stock" => $data["stock"],
                "price" => $data["price"],
                "cost_price"=>$data["cost_price"],
                "is_show_stock" => $data["is_show_stock"],
                "spec_type" => $data["spec_type"],
                "spec_data" => isset($data["add_spec_arr"]) ? json_encode($data["add_spec_arr"]) : "",
                "big_img" => $data["big_img"],
                "carousel_img" => $data["carousel_img"],
                "recommend_img" => $data["recommend_img"],
                "is_home_recommend" => 1,
            ]);
            if ($id <= 0) {
                $id = $this->model->id;
            }

            if ($data["spec_type"] == "2" && !empty($data["skus"])) {
                $index = 1;
                $insertData = [];
                foreach ($data["skus"] as $sku){
                    $insertData[] = [
                        "sku" => !empty($sku["spec_value_ids"]["sku"]) ? $sku["spec_value_ids"]["sku"] : sprintf("%s-%d", $data["sku"], $index),
                        "product_id" => $id,
                        "spec_value_ids" => $sku["spec_value_ids"]["propvalids"],
                        "price" => $sku["spec_value_ids"]["skuPrice"],
                        "cost_price" => $sku["spec_value_ids"]["skuCostPrice"],
                        "stock" => $sku["spec_value_ids"]["skuStock"],
                    ];
                    $index++;
                }
                $this->skuModel->saveAll($insertData);
            }
            Db::commit();
        }catch (Exception $e){
            Log::error($e);
            Db::rollback();
            return false;
        }


        return true;
    }
}